package com.example.demo3userdetailsservicedatabase.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
    /**
     * 如果下面不用http.userDetailsService(userDetailsService)指定，这里可以不定义
     * 本例中的userDetailsService 来自com.example.demo3userdetailsservicedatabase.service.UserDetailsServiceImpl
     */
//    private final UserDetailsService userDetailsService;
    /**
     * 这个bean可以不定义，默认就是这样的方式。加密使用的bcrypt。
     * 获取一个加密字符串 PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("123456")
     * 比如本实例中就用了两种加密方式, 密码验证时会根据前缀进行验证
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // login放行，其他请求验证
        http.authorizeHttpRequests(authorize->authorize.requestMatchers("login").permitAll().anyRequest().authenticated());
        // 请求参数用username和password
        http.formLogin(Customizer.withDefaults());
        /**
         * 这里如果指定需要定义userDetailsService，如果不指定，系统会自动找UserDetailsService的实例对象
         */
//        http.userDetailsService(userDetailsService);
        http.csrf(csrf->csrf.disable());
        return http.build();

    }
}
